package com.cn.hnust.filter;
 
import java.io.IOException;
import java.util.ArrayList;
 
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
/**
 * Servlet Filter implementation class LoginFilter
 */
@WebFilter("/LoginFilter")
public class LoginFilter implements Filter {
	public static final String login_page = "/index.jsp";
	public static final String logout_page = "/index.jsp";
	
	//涓嶈鎷︽埅鐨勯〉闈�
	private static ArrayList<String> initPages = new ArrayList<String>();
	static {
		initPages.add("/index.jsp");
		initPages.add("/register.jsp");
	}
 
	/**
	 * Default constructor.
	 */
	public LoginFilter() {
		// TODO Auto-generated constructor stub
	}
 
	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}
 
	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		String currentURL = request.getRequestURI();
		String ctxPath = request.getContextPath();
		// 闄ゆ帀椤圭洰鍚嶇О鏃惰闂〉闈㈠綋鍓嶈矾寰�
		String targetURL = currentURL.substring(ctxPath.length());
		HttpSession session = request.getSession(false);
            //鍒ゆ柇鏄惁涓� 涓嶈鎷︽埅鐨勭晫闈�
		Boolean isInitPage = false;
		for (int i = 0; i < initPages.size();i++) {
			String initPage = initPages.get(i);
			System.out.print("\ninitPage:  " + initPage);
			if (initPage.equals(targetURL)) {
				isInitPage = true;
			}
		}
 
		if (!isInitPage) {
			System.out.println(
					"\ntargetURL:   " + targetURL + "\nctxPath:   " + ctxPath + "\ncurrentURL:   " + currentURL);
			// 鍦ㄤ笉涓虹櫥闄嗛〉闈㈡椂锛屽啀杩涜鍒ゆ柇锛屽鏋滀笉鏄櫥闄嗛〉闈篃娌℃湁session鍒欒烦杞埌鐧诲綍椤甸潰锛�
			if (session == null || session.getAttribute("user") == null) {
				response.sendRedirect("/index1.jsp");
				return;
			} else {
				// 杩欓噷琛ㄧず姝ｇ‘锛屼細鍘诲鎵句笅涓�涓摼锛屽鏋滀笉瀛樺湪锛屽垯杩涜姝ｅ父鐨勯〉闈㈣烦杞�
				chain.doFilter(request, response);
				return;
			}
		} else {
			chain.doFilter(request, response);
			return;
		}
 
 
	}
 
	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}
 
}
